<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
<meta name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">

    <meta name="author" content="豆豆">


    <meta name="subtitle" content="愿望是实现睡觉自由">


    <meta name="description" content="你来啦，这里是豆豆的小笔记！">


    <meta name="keywords" content="豆豆,学习,小笔记,睡觉自由">


<title>「Go_05」基本数据类型 | 豆豆的小笔记</title>



    <link rel="icon" href="/favicon.ico">




    <!-- stylesheets list from _config.yml -->
    
    <link rel="stylesheet" href="/css/style.css">
    



    <!-- scripts list from _config.yml -->
    
    <script src="/js/script.js"></script>
    
    <script src="/js/tocbot.min.js"></script>
    



    
    
        
    


<meta name="generator" content="Hexo 4.2.0"></head>
<body>
    <div class="wrapper">
        <header>
    <nav class="navbar">
        <div class="container">
            <div class="navbar-header header-logo"><a href="/">豆豆的小笔记</a></div>
            <div class="menu navbar-right">
                
                    <a class="menu-item" href="/archives">归档</a>
                
                    <a class="menu-item" href="/category">分类</a>
                
                    <a class="menu-item" href="/tag">标签</a>
                
                    <a class="menu-item" href="/about">关于</a>
                
                <input id="switch_default" type="checkbox" class="switch_default">
                <label for="switch_default" class="toggleBtn"></label>
            </div>
        </div>
    </nav>

    
    <nav class="navbar-mobile" id="nav-mobile">
        <div class="container">
            <div class="navbar-header">
                <div>
                    <a href="/">豆豆的小笔记</a><a id="mobile-toggle-theme">·&nbsp;纯白</a>
                </div>
                <div class="menu-toggle" onclick="mobileBtn()">&#9776; 菜单</div>
            </div>
            <div class="menu" id="mobile-menu">
                
                    <a class="menu-item" href="/archives">归档</a>
                
                    <a class="menu-item" href="/category">分类</a>
                
                    <a class="menu-item" href="/tag">标签</a>
                
                    <a class="menu-item" href="/about">关于</a>
                
            </div>
        </div>
    </nav>

</header>
<script>
    var mobileBtn = function f() {
        var toggleMenu = document.getElementsByClassName("menu-toggle")[0];
        var mobileMenu = document.getElementById("mobile-menu");
        if(toggleMenu.classList.contains("active")){
           toggleMenu.classList.remove("active")
            mobileMenu.classList.remove("active")
        }else{
            toggleMenu.classList.add("active")
            mobileMenu.classList.add("active")
        }
    }
</script>
        <div class="main">
            <div class="container">
    
    
        <div class="post-toc">
    <div class="tocbot-list">
    </div>
    <div class="tocbot-list-menu">
        <a class="tocbot-toc-expand" onclick="expand_toc()">展开所有</a>
        <a onclick="go_top()">回到顶部</a>
        <a onclick="go_bottom()">到达底部</a>
    </div>
</div>

<script>
    document.ready(
        function () {
            tocbot.init({
                tocSelector: '.tocbot-list',
                contentSelector: '.post-content',
                headingSelector: 'h1, h2, h3, h4, h5',
                collapseDepth: 1,
                orderedList: false,
                scrollSmooth: true,
            })
        }
    )

    function expand_toc() {
        var b = document.querySelector(".tocbot-toc-expand");
        tocbot.init({
            tocSelector: '.tocbot-list',
            contentSelector: '.post-content',
            headingSelector: 'h1, h2, h3, h4, h5',
            collapseDepth: 6,
            orderedList: false,
            scrollSmooth: true,
        });
        b.setAttribute("onclick", "collapse_toc()");
        b.innerHTML = "收起所有"
    }

    function collapse_toc() {
        var b = document.querySelector(".tocbot-toc-expand");
        tocbot.init({
            tocSelector: '.tocbot-list',
            contentSelector: '.post-content',
            headingSelector: 'h1, h2, h3, h4, h5',
            collapseDepth: 1,
            orderedList: false,
            scrollSmooth: true,
        });
        b.setAttribute("onclick", "expand_toc()");
        b.innerHTML = "展开所有"
    }

    function go_top() {
        window.scrollTo(0, 0);
    }

    function go_bottom() {
        window.scrollTo(0, document.body.scrollHeight);
    }

</script>
    

    
    <article class="post-wrap">
        <header class="post-header">
            <h1 class="post-title">「Go_05」基本数据类型</h1>
            
                <div class="post-meta">
                    

                    
                        <span class="post-time">
                        时间： <a href="#">三月 10, 2020&nbsp;&nbsp;21:58:57</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        </span>
                    
                    
                        <span class="post-category">
                    分类：
                            
                                <a href="/categories/Go/">Go</a>
                            
                        </span>
                    
                </div>
            
        </header>

        <div class="post-content">
            <h1 id="整形"><a href="#整形" class="headerlink" title="整形"></a>整形</h1><h2 id="普通整形"><a href="#普通整形" class="headerlink" title="普通整形"></a>普通整形</h2><p>整型分为以下两个大类： </p>
<ol>
<li>有符号整形按长度分为：<code>int8</code>、<code>int16</code>、<code>int32</code>、<code>int64</code> 。</li>
<li>对应的无符号整型：<code>uint8</code>、<code>uint16</code>、<code>uint32</code>、<code>uint64</code>。</li>
</ol>
<blockquote>
<ul>
<li><code>uint8</code>就是我们熟知的<code>byte</code>型。</li>
<li><code>int16</code>对应C语言中的<code>short</code>型。</li>
<li><code>int64</code>对应C语言中的<code>long</code>型。</li>
</ul>
</blockquote>
<table>
<thead>
<tr>
<th align="center">类型</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center">uint8</td>
<td align="center">无符号 8位整型 (0 到 255)</td>
</tr>
<tr>
<td align="center">uint16</td>
<td align="center">无符号 16位整型 (0 到 65535)</td>
</tr>
<tr>
<td align="center">uint32</td>
<td align="center">无符号 32位整型 (0 到 4294967295)</td>
</tr>
<tr>
<td align="center">uint64</td>
<td align="center">无符号 64位整型 (0 到 18446744073709551615)</td>
</tr>
<tr>
<td align="center">int8</td>
<td align="center">有符号 8位整型 (-128 到 127)</td>
</tr>
<tr>
<td align="center">int16</td>
<td align="center">有符号 16位整型 (-32768 到 32767)</td>
</tr>
<tr>
<td align="center">int32</td>
<td align="center">有符号 32位整型 (-2147483648 到 2147483647)</td>
</tr>
<tr>
<td align="center">int64</td>
<td align="center">有符号 64位整型 (-9223372036854775808 到 9223372036854775807)</td>
</tr>
</tbody></table>
<h2 id="特殊整形"><a href="#特殊整形" class="headerlink" title="特殊整形"></a>特殊整形</h2><table>
<thead>
<tr>
<th align="center">类型</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center">uint</td>
<td align="center">32位操作系统上就是<code>uint32</code>，64位操作系统上就是<code>uint64</code></td>
</tr>
<tr>
<td align="center">int</td>
<td align="center">32位操作系统上就是<code>int32</code>，64位操作系统上就是<code>int64</code></td>
</tr>
<tr>
<td align="center">uintptr</td>
<td align="center">无符号整型，用于存放一个指针</td>
</tr>
</tbody></table>
<blockquote>
<p><strong>注意：</strong> </p>
<ol>
<li>在使用<code>int</code>和 <code>uint</code>类型时，不能假定它是32位或64位的整型，而是考虑<code>int</code>和<code>uint</code>可能在<strong>不同平台上的差异</strong>。</li>
<li>获取对象的长度的内建<code>len()</code>函数返回的长度可以根据不同平台的字节长度进行变化。</li>
<li>实际使用中，切片或 map 的元素数量等都可以用<code>int</code>来表示。</li>
<li>在涉及到二进制传输、读写文件的结构描述时，为了保持文件的结构不会受到不同编译目标平台字节长度的影响，不要使用<code>int</code>和 <code>uint</code>。</li>
</ol>
</blockquote>
<h2 id="数字字面量语法（Number-literals-syntax）"><a href="#数字字面量语法（Number-literals-syntax）" class="headerlink" title="数字字面量语法（Number literals syntax）"></a>数字字面量语法（Number literals syntax）</h2><p>Go1.13版本之后引入了数字字面量语法，这样便于开发者以<strong>二进制</strong>、<strong>八进制</strong>或<strong>十六进制</strong>浮点数的格式定义数字，例如：</p>
<ul>
<li>v := 0b00101101， 代表二进制的 101101，相当于十进制的 45。</li>
<li>v := 0o377，代表八进制的 377，相当于十进制的 255。</li>
<li>v := 0x1p-2，代表十六进制的 1 除以 2²，也就是 0.25。 </li>
<li>而且还允许我们用 _ 来分隔数字，比如说：v := 123_456 等于 123456。</li>
</ul>
<p>我们可以借助fmt函数来将一个整数以不同进制形式展示。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">	<span class="comment">// 十进制</span></span><br><span class="line">	<span class="keyword">var</span> a <span class="keyword">int</span> = <span class="number">10</span></span><br><span class="line">	fmt.Printf(<span class="string">"%d \n"</span>, a)  <span class="comment">// 10</span></span><br><span class="line">	fmt.Printf(<span class="string">"%b \n"</span>, a)  <span class="comment">// 1010  占位符%b表示二进制</span></span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 八进制  以0开头</span></span><br><span class="line">	<span class="keyword">var</span> b <span class="keyword">int</span> = <span class="number">077</span></span><br><span class="line">	fmt.Printf(<span class="string">"%o \n"</span>, b)  <span class="comment">// 77</span></span><br><span class="line"> </span><br><span class="line">	<span class="comment">// 十六进制  以0x开头</span></span><br><span class="line">	<span class="keyword">var</span> c <span class="keyword">int</span> = <span class="number">0xff</span></span><br><span class="line">	fmt.Printf(<span class="string">"%x \n"</span>, c)  <span class="comment">// ff</span></span><br><span class="line">	fmt.Printf(<span class="string">"%X \n"</span>, c)  <span class="comment">// FF</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 查看变量类型</span></span><br><span class="line">    fmt.Printf(<span class="string">"%T \n"</span>, c)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="浮点型"><a href="#浮点型" class="headerlink" title="浮点型"></a>浮点型</h1><p>Go语言支持两种浮点型数：<code>float32</code>和<code>float64</code>。这两种浮点型数据格式遵循<code>IEEE 754</code>标准：</p>
<ol>
<li><code>float32</code> 的浮点数的最大范围约为 <code>3.4e38</code>，可以使用常量定义：<code>math.MaxFloat32</code>。</li>
<li><code>float64</code> 的浮点数的最大范围约为 <code>1.8e308</code>，可以使用一个常量定义：<code>math.MaxFloat64</code>。</li>
</ol>
<blockquote>
<p><strong>注意</strong>：</p>
<ul>
<li><code>float32</code>类型的值不能直接赋值给<code>float64</code>类型的值。</li>
<li>浮点型数默认类型是<code>float64</code>，以保证更加精确。</li>
</ul>
</blockquote>
<p>打印浮点数时，可以使用<code>fmt</code>包配合动词<code>%f</code>，代码如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">        <span class="string">"fmt"</span></span><br><span class="line">        <span class="string">"math"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        fmt.Printf(<span class="string">"%f\n"</span>, math.Pi)</span><br><span class="line">        fmt.Printf(<span class="string">"%.2f\n"</span>, math.Pi)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="复数"><a href="#复数" class="headerlink" title="复数"></a>复数</h1><p>有<code>complex64</code>和<code>complex128</code>两种类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> c1 <span class="keyword">complex64</span></span><br><span class="line">c1 = <span class="number">1</span> + <span class="number">2i</span></span><br><span class="line"><span class="keyword">var</span> c2 <span class="keyword">complex128</span></span><br><span class="line">c2 = <span class="number">2</span> + <span class="number">3i</span></span><br><span class="line">fmt.Println(c1)</span><br><span class="line">fmt.Println(c2)</span><br></pre></td></tr></table></figure>

<p>复数有实部和虚部，<code>complex64</code>的实部和虚部为32位，<code>complex128</code>的实部和虚部为64位。</p>
<h1 id="布尔值"><a href="#布尔值" class="headerlink" title="布尔值"></a>布尔值</h1><p>Go语言中以<code>bool</code>类型进行声明布尔型数据，布尔型数据只有<code>true</code>（真）和<code>false</code>（假）两个值。</p>
<blockquote>
<p><strong>注意：</strong></p>
<ul>
<li>布尔类型变量的默认值为<code>false</code>。</li>
<li>Go 语言中不允许将整型强制转换为布尔型.</li>
<li>布尔型无法参与数值运算，也无法与其他类型进行转换。</li>
</ul>
</blockquote>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        b1 := <span class="literal">true</span></span><br><span class="line">        <span class="keyword">var</span> b2 <span class="keyword">bool</span> <span class="comment">// 默认值是false</span></span><br><span class="line">        fmt.Printf(<span class="string">"%T\n"</span>, b1)</span><br><span class="line">        <span class="comment">// %v可以将任何类型的值输出</span></span><br><span class="line">        fmt.Printf(<span class="string">"%T value:%v\n"</span>, b2, b2)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h1><p>Go语言中的字符串以原生数据类型出现，使用字符串就像使用其他原生数据类型<code>int</code>、<code>bool</code>、<code>float32</code>、<code>float64</code>等一样。 </p>
<p>Go 语言里的字符串的内部实现使用<code>UTF-8</code>编码，<strong>支持中文</strong>。 </p>
<p>字符串的值<strong>只能</strong>用双引号<code>&quot; &quot;</code>引起，可以在Go语言的源码中直接添加<strong>非ASCII码</strong>字符，例如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">s1 := <span class="string">"hello"</span></span><br><span class="line">s2 := <span class="string">"你好"</span></span><br></pre></td></tr></table></figure>

<h2 id="字符串转义符"><a href="#字符串转义符" class="headerlink" title="字符串转义符"></a>字符串转义符</h2><p>Go 语言的字符串常见转义符包含回车、换行、单双引号、制表符等，如下表所示：</p>
<table>
<thead>
<tr>
<th align="center">转义符</th>
<th align="center">含义</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>\r</code></td>
<td align="center">回车符（返回行首）</td>
</tr>
<tr>
<td align="center"><code>\n</code></td>
<td align="center">换行符（直接跳到下一行的同列位置）</td>
</tr>
<tr>
<td align="center"><code>\t</code></td>
<td align="center">制表符</td>
</tr>
<tr>
<td align="center"><code>\&#39;</code></td>
<td align="center">单引号</td>
</tr>
<tr>
<td align="center"><code>\&quot;</code></td>
<td align="center">双引号</td>
</tr>
<tr>
<td align="center"><code>\\</code></td>
<td align="center">反斜杠</td>
</tr>
</tbody></table>
<p>举个例子，我们要打印一个Windows平台下的一个文件路径：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    fmt.Println(<span class="string">"str := \"c:\\Code\\lesson1\\go.exe\""</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="多行字符串"><a href="#多行字符串" class="headerlink" title="多行字符串"></a>多行字符串</h2><p>Go语言中要定义一个多行字符串时，就必须使用反引号<code>`</code>字符：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">s1 := <span class="string">`第一行</span></span><br><span class="line"><span class="string">第二行</span></span><br><span class="line"><span class="string">第三行</span></span><br><span class="line"><span class="string">`</span></span><br><span class="line">fmt.Println(s1)</span><br></pre></td></tr></table></figure>

<p>反引号间换行将被作为字符串中的换行，但是所有的<strong>转义字符均无效</strong>，文本将会原样输出。</p>
<h2 id="字符串的常用操作"><a href="#字符串的常用操作" class="headerlink" title="字符串的常用操作"></a>字符串的常用操作</h2><table>
<thead>
<tr>
<th align="center">方法</th>
<th align="center">介绍</th>
</tr>
</thead>
<tbody><tr>
<td align="center">len(str)</td>
<td align="center">求长度</td>
</tr>
<tr>
<td align="center">+或fmt.Sprintf</td>
<td align="center">拼接字符串</td>
</tr>
<tr>
<td align="center">strings.Split</td>
<td align="center">分割</td>
</tr>
<tr>
<td align="center">strings.contains</td>
<td align="center">判断是否包含</td>
</tr>
<tr>
<td align="center">strings.HasPrefix,strings.HasSuffix</td>
<td align="center">前缀/后缀判断</td>
</tr>
<tr>
<td align="center">strings.Index(),strings.LastIndex()</td>
<td align="center">子串出现的位置</td>
</tr>
<tr>
<td align="center">strings.Join(a[]string, sep string)</td>
<td align="center">join操作</td>
</tr>
</tbody></table>
<h1 id="byte和rune类型"><a href="#byte和rune类型" class="headerlink" title="byte和rune类型"></a>byte和rune类型</h1><p>组成每个字符串的元素叫做“字符”，可以通过遍历或者单个获取字符串元素获得字符。 </p>
<p>字符可以是单独的字母、<strong>汉字</strong>或符号，不一定是一个字节。</p>
<p>字符用单引号<code>&#39; &#39;</code>包裹起来，如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a := <span class="string">'中'</span></span><br><span class="line"><span class="keyword">var</span> b := <span class="string">'x'</span></span><br></pre></td></tr></table></figure>

<p>Go 语言的字符有以下两种：</p>
<ol>
<li><code>byte</code> 类型，实际上是<code>uint8</code>类型，代表了一个ASCII码字符。</li>
<li><code>rune</code>类型，实际上是<code>int32</code>类型，代表一个 UTF-8字符。</li>
</ol>
<p>当需要处理中文、日文或者其他复合字符时，则需要用到<code>rune</code>类型。</p>
<ul>
<li>Go 使用了特殊的<code>rune</code>类型来处理 Unicode，让基于 Unicode 的文本处理更为方便。</li>
<li>也可以使用<code>byte</code> 型进行默认字符串处理，性能和扩展性都有照顾。</li>
</ul>
<h2 id="遍历字符串"><a href="#遍历字符串" class="headerlink" title="遍历字符串"></a>遍历字符串</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 遍历字符串</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">traversalString</span><span class="params">()</span></span> &#123;</span><br><span class="line">	s := <span class="string">"hello沙河"</span></span><br><span class="line">	<span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="built_in">len</span>(s); i++ &#123; <span class="comment">//byte</span></span><br><span class="line">		fmt.Printf(<span class="string">"%v(%c) "</span>, s[i], s[i])</span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Println()</span><br><span class="line">	<span class="keyword">for</span> _, r := <span class="keyword">range</span> s &#123; <span class="comment">//rune</span></span><br><span class="line">		fmt.Printf(<span class="string">"%v(%c) "</span>, r, r)</span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Println()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">104(h) 101(e) 108(l) 108(l) 111(o) 230(æ) 178(²) 153() 230(æ) 178(²) 179(³) </span><br><span class="line">104(h) 101(e) 108(l) 108(l) 111(o) 27801(沙) 27827(河)</span><br></pre></td></tr></table></figure>

<p>因为UTF8编码下一个中文汉字由3~4个字节组成，所以不能简单的按照字节去遍历一个包含中文的字符串，否则就会出现上面输出中第一行的结果。</p>
<blockquote>
<ul>
<li>字符串底层是一个<code>byte</code>数组，所以可以和<code>[]byte</code>类型相互转换。</li>
<li>字符串是不能修改的，字符串是由<code>byte</code>字节组成，所以<strong>字符串的长度是<code>byte</code>字节的长度</strong>。</li>
<li><code>rune</code>类型用来表示UTF8字符，一个<code>rune</code>字符由一个或多个<code>byte</code>组成。</li>
</ul>
</blockquote>
<h2 id="修改字符串"><a href="#修改字符串" class="headerlink" title="修改字符串"></a>修改字符串</h2><p>要修改字符串，需要先将其转换成<code>[]rune</code>或<code>[]byte</code>，完成后再转换为<code>string</code>。无论哪种转换，都会重新分配内存，并复制字节数组。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">changeString</span><span class="params">()</span></span> &#123;</span><br><span class="line">	s1 := <span class="string">"big"</span></span><br><span class="line">	<span class="comment">// 强制类型转换</span></span><br><span class="line">	byteS1 := []<span class="keyword">byte</span>(s1)</span><br><span class="line">	byteS1[<span class="number">0</span>] = <span class="string">'p'</span></span><br><span class="line">	fmt.Println(<span class="keyword">string</span>(byteS1))</span><br><span class="line"></span><br><span class="line">	s2 := <span class="string">"白萝卜"</span></span><br><span class="line">	runeS2 := []<span class="keyword">rune</span>(s2)</span><br><span class="line">	runeS2[<span class="number">0</span>] = <span class="string">'红'</span></span><br><span class="line">	fmt.Println(<span class="keyword">string</span>(runeS2))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="类型转换"><a href="#类型转换" class="headerlink" title="类型转换"></a>类型转换</h1><p>Go语言中<strong>只有强制类型转换</strong>，没有隐式类型转换。该语法只能在两个类型之间<strong>支持</strong>相互转换的时候使用。</p>
<p>强制类型转换的基本语法如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">T(表达式)</span><br></pre></td></tr></table></figure>

<p>其中，T表示要转换的类型。表达式包括变量、复杂算子和函数返回值等.</p>
<p>比如计算直角三角形的斜边长时使用math包的Sqrt()函数，该函数接收的是float64类型的参数，而变量a和b都是int类型的，这个时候就需要将a和b强制类型转换为float64类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sqrtDemo</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> a, b = <span class="number">3</span>, <span class="number">4</span></span><br><span class="line">	<span class="keyword">var</span> c <span class="keyword">int</span></span><br><span class="line">	<span class="comment">// math.Sqrt()接收的参数是float64类型，需要强制转换</span></span><br><span class="line">	c = <span class="keyword">int</span>(math.Sqrt(<span class="keyword">float64</span>(a*a + b*b)))</span><br><span class="line">	fmt.Println(c)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
        </div>

        
        <section class="post-tags">
            <div>
                <span>标签：</span>
                <span class="tag">
                    
                    
                        <a href="/tags/Go/"># Go</a>&nbsp;&nbsp;
                    
                        <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/"># 编程语言</a>&nbsp;&nbsp;
                    
                        
                </span>
            </div>
            <div>
                <a href="javascript:window.history.back();">返回</a>
                <span>· </span>
                <a href="/">主页</a>
            </div>
        </section>
        <section class="post-nav">
            
                <a class="prev" rel="prev" href="/2020/03/10/go-06/">「Go_06」运算符</a>
            
            
            <a class="next" rel="next" href="/2020/03/09/go-04/">「Go_04」变量与常量</a>
            
        </section>


    </article>
</div>

        </div>
        <footer id="footer" class="footer">
    <div class="copyright">
        <span>© 豆豆 | Powered by <a href="https://hexo.io" target="_blank">Hexo</a> & <a href="https://github.com/Siricee/hexo-theme-Chic" target="_blank">Chic</a></span>
    </div>
</footer>


    <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
    <script>
      if (window.mermaid) {
        mermaid.initialize({theme: 'neutral'});
      }
    </script>
  
    </div>
</body>
</html>
